import axios from 'axios'
import store from '@/store'
// import { getCookie } from 'cookie'

// create an axios instance
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    timeout: 5000, // request timeout
    withCredentials: true,// 允许携带cookie
    crossDomain: true
})

// request interceptor
service.interceptors.request.use(
    config => {
        // do something before request is sent
        config.headers.USER = getCookie('token');
        return config
    },
    error => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    /**
     * If you want to get http information such as headers or status
     * Please return  response => response
     */

    /**
     * Determine the request status by custom code
     * Here is just an example
     * You can also judge the status by HTTP Status Code
     */
    response => {
        const res = response.data
        // store.commit('SET_LOADING',false);

        // if the custom code is not 20000, it is judged as an error.
        // if (res.code !== 200) {
        //     console.log(res)
        // } else {
        //     return res
        // }
        return res
    },
    error => {
        console.log('err' + error) // for debug
        return Promise.reject(error)
    }
)

export default service
//获取cookie
export function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    // console.log("获取cookie,现在循环")
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        // console.log(c)
        while (c.charAt(0) == ' ') c = c.substring(1);
        if (c.indexOf(name) != -1){
            return c.substring(name.length, c.length);
        }
    }
    return "";
}